package com.magicalcoder.youyamvc.web.interceptor;

import com.magicalcoder.youyamvc.app.common.StatusConstant;
import com.magicalcoder.youyamvc.core.common.exception.BusinessException;
import com.magicalcoder.youyamvc.core.common.utils.log.Log4jUtils;
import com.magicalcoder.youyamvc.core.spring.JsonWrite;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;

@RestControllerAdvice
public class ExceptionHandlerAdvice extends JsonWrite {

    private final static Logger logger = Log4jUtils.getLog(ExceptionHandlerAdvice.class);

    @ExceptionHandler
    public void handler(HttpServletRequest req, HttpServletResponse res, Exception e) {
        if(e instanceof BusinessException){
            logger.error("BusinessException：" + e.getMessage(), e);
            toWebExceptionJson(res,((BusinessException) e).getErrorCode(),((BusinessException) e).getErrorMessage());
            return;
        }
        else if (e instanceof NullPointerException) {
            logger.error("NullPointerException：" + e.getMessage(), e);
            toWebExceptionJson(res, StatusConstant.EXCEPTION_ERROR_CODE_NULL_POINT);
            return;
        } else if (e instanceof IllegalArgumentException) {
            logger.error("IllegalArgumentException：" + e.getMessage(), e);
            toWebExceptionJson(res, StatusConstant.EXCEPTION_ERROR_CODE_ILLEGAL_ARGUMENT);
            return;
        } else if (e instanceof SQLException) {
            logger.error("SQLException：" + e.getMessage(), e);
            toWebExceptionJson(res, StatusConstant.EXCEPTION_ERROR_CODE_SQL);
            return;
        } else {
            logger.error("Exception：" + e.getMessage(), e);
            toWebExceptionJson(res, StatusConstant.EXCEPTION_ERROR_CODE);
            return;
        }
    }
}